package com.fpost.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.Globals;

import com.fpost.constants.ActionConstants;
import com.fpost.constants.CommonConstants;
import com.fpost.form.dto.UserDTO;
import com.fpost.security.ActionSecurityUtils;
import com.fpost.util.CommonUtils;

public class FpostFilter implements Filter {

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		
		//Get init parameter
        //String testParam = config.getInitParameter("test-param"); 
        //Print the init parameter
        //System.out.println("Test Param: " + testParam);
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpServletRequest request = (HttpServletRequest) req;
		request.setCharacterEncoding(CommonConstants.UTF8);
		
		// set default locale
		if (request.getSession().getAttribute(Globals.LOCALE_KEY) == null) {
			request.getSession().setAttribute(Globals.LOCALE_KEY, new Locale("uk", ""));
			request.getSession().setAttribute(ActionConstants.CURRENT_LANG, "uk");
		}
		//System.out.println(request.getLocale().getLanguage());
		//System.out.println(((Locale)request.getSession().getAttribute(Globals.LOCALE_KEY)).getLanguage());
		
		UserDTO userDTO = ActionSecurityUtils.getUserDTO_fromSession(request);
		if (userDTO != null) {
			request.setAttribute(CommonConstants.USER_ID, userDTO.getUserId());
			request.setAttribute(CommonConstants.USERNAME, userDTO.getUsername());
			request.setAttribute(CommonConstants.FIRST_NAME, userDTO.getFirstName());
			request.setAttribute(CommonConstants.LAST_NAME, userDTO.getLastName());
		}
		
		//System.out.println("\nURL " + request.getRequestURL());
		//System.out.println("URI " + request.getRequestURI());
		
		//persist IP address of client machine
		CommonUtils.saveIpAddress(null, request);
 
        chain.doFilter(req, res);
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
